<?php
class Search extends MY_SecuredController{
	function __construct() {
		parent::MY_SecuredController();

		$this->requireRole('Admin');

		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
		$this->load->library('formdate');
	}

	public function index() {
		$this->_preRender(Current_User::user()->id);

		if (!$this->input->post('action')) {
			$this->render('admin/search/search');
		}
		else {
			if ($this->_submit_search_validate() === FALSE) {
				$data = array();
				$this->render('admin/search/search', $data, $this->error(validation_errors('<li>','</li>')));
			}
			else {
				$params = '/'.$this->input->post('criteria').'/'.$this->input->post('type').'/'.$this->input->post('term');

				$this->redirect('admin/search/query'.$params);
			}
		}
	}

	public function query($criteria, $type, $term) {
		// @todo: add argument check

		log_message('debug', 'Person::search criteria: '.$criteria);

		if ($criteria == 'civl_id') {
			$results = PersonModel::findByCivlId($term, $type);
		}
		else {
			$results = PersonModel::findByName($term, $type);
		}

		$data['results'] = $results;
		$data['criteria'] = $criteria;
		$data['type'] = $type;
		$data['term'] = $term;

		$this->render('admin/search/search', $data);
	}
	
	public function back($url) {
		$data['forward_url'] = $url;
		
        $this->_preRender(Current_User::user()->id);

        if (!$this->input->post('action')) {
            $this->render('admin/search/search', $data);
        }
        else {
            if ($this->_submit_search_validate() === FALSE) {
                $data = array();
                $this->render('admin/search/search', $data, $this->error(validation_errors('<li>','</li>')));
            }
            else {
                $params = '/'.$this->input->post('criteria').'/'.$this->input->post('type').'/'.$this->input->post('term');

                $this->redirect('admin/search/query'.$params);
            }
        }
	}

	private function _submit_search_validate() {
		$this->form_validation->set_rules('term', 'value in the textfield', 'required');
		$this->form_validation->set_rules('criteria', 'Criteria', 'required');
		$this->form_validation->set_rules('type', 'Type', 'required');

		return $this->form_validation->run();
	}

}